package com.cloudm.technician.ui.modules.common.login

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.view.MenuItem
import com.cloudm.technician.R
import com.cloudm.technician.data.config.Config
import com.cloudm.technician.extensions.addFragmentToActivity
import com.cloudm.technician.extensions.openActivity
import com.cloudm.technician.ui.base.BaseActivity
import com.cloudm.technician.ui.modules.common.register.RegisterActivity

/**
 * 作者: wesley
 * 时间: 2017/12/13
 * 描述: 登陆界面
 */
class LoginActivity : BaseActivity() {

    override val optionsMenuEnabled: Boolean
        get() = true

    private val intentFilter: IntentFilter by lazy {
        IntentFilter().apply {
            addAction(Config.ACTION_LOGIN)
        }
    }

    private val receiver: LoginBroadcastReceiver by lazy {
        LoginBroadcastReceiver()
    }


    override fun handleBundle(bundle: Bundle) {

    }

    override fun initVariables() {

    }

    override fun initViews(savedInstanceState: Bundle?) {
        headerTitle = R.string.login
        displayHomeAsUpEnabled = true

        val fragment = manager.findFragmentById(
                R.id.common_content) as? LoginFragment ?: LoginFragment.newInstance()
        addFragmentToActivity(manager, fragment)

        registerLoginReceiver()
    }

    override fun initListener() {

    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        return when (item?.itemId) {
            R.id.menu_next -> {
                openActivity(RegisterActivity::class.java, false)
                true
            }

            else -> {
                false
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(receiver)
    }


    private fun registerLoginReceiver() {
        registerReceiver(receiver, intentFilter)
    }

    private inner class LoginBroadcastReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            finish()
        }
    }

}